﻿using System;
using System.Windows.Forms;

namespace CodePlex.DnD4eCampaignManager.ControlLibrary
{
    public partial class DDIBrowser : Form
    {
        public DDIBrowser()
        {
            InitializeComponent();
        }

        public string MonsterHtml { get; set; }

        public void NavigateToMonsterId(int monsterId)
        {
            string uri = string.Format("http://ww2.wizards.com/dnd/insider/monster.aspx?id={0}", monsterId);
            monsterBrowser.Url = new Uri(uri);
        }

        public void SearchForMonster(string monsterName)
        {
            string uri = string.Format("http://ww2.wizards.com/dnd/insider/database.aspx?searchterm={0}#tab=monsters", monsterName);
            monsterBrowser.Url = new Uri(uri);
        }

        private void monsterBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string url = monsterBrowser.Url.AbsoluteUri;
            toolStripUrlText.Text = url;

            toolStripImportButton.Enabled = false;
            toolStripMonsterIdText.Text = "N/A";

            if ( url.ToLower().Contains("monster.aspx") )
            {
                int idx = url.IndexOf("monster.aspx");
                string monsterId = url.Substring(idx);
                idx = url.IndexOf("id=");
                monsterId = url.Substring(idx + 3);
                toolStripMonsterIdText.Text = monsterId;

                toolStripImportButton.Enabled = true;
            }
        }

        private void toolStripImportButton_Click(object sender, EventArgs e)
        {
            MonsterHtml = monsterBrowser.DocumentText;
            DialogResult = DialogResult.OK;
        }

        private void toolStripMonsterIdText_KeyUp(object sender, KeyEventArgs e)
        {
            if ( e.KeyCode == Keys.Enter )
            {
                int monsterId;
                if ( Int32.TryParse(toolStripMonsterIdText.Text, out monsterId) )
                {
                    NavigateToMonsterId(monsterId);
                    e.Handled = true;
                }
            }
        }

        private void toolStripUrlText_KeyUp(object sender, KeyEventArgs e)
        {
            if ( e.KeyCode == Keys.Enter )
            {
                monsterBrowser.Url = new Uri(toolStripUrlText.Text);
                e.Handled = true;
            }
        }
    }
}